<template>
  <div>
    <!--    标题-->
    <div class="block">{{ uploadTitle }}</div>
    <!--    控件-->
    <el-upload
      class="avatar-uploader"
      action="/api/upload"
      :headers="headers"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>

export default {
  name: 'Index',
  props: {
    uploadTitle: {
      type: String
    },
    value: {
      type: String
    }
  },
  computed: {
    imgUrl() {
      if (this.value) {
        return this.value
      }
      return null
    },
    headers() {
      return {
        Authorization: 'Bearer ' + this.$store.getters.token
      }
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      // 成功之后
      if (!res.code && res.data) {
        this.$emit('input', res.data)
        // 向上传递为input事件，因为v-model默认绑定的是input事件，从而双向绑定导致值改变
      }
    },
    beforeAvatarUpload() {
      // 上传之前
      this.$emit('beforeAvatarUpload')
    }
  }
}
</script>

<style lang="scss" scoped>
.block{
  margin: 15px 0;
  font-weight: 100;
}
.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
